<template>
  <div class="chart" ref="chartRef"></div>
</template>

<script setup>
import { ref, onMounted, watch, onUnmounted } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
  chartData: {
    type: Object,
    required: true
  },
  chartType: {
    type: String,
    default: 'week'
  },
  theme: {
    type: String,
    default: 'light'
  }
});

const chartRef = ref(null);
let chart = null;

function initChart() {
  if (!chartRef.value) return;
  
  // 销毁旧图表
  if (chart) {
    chart.dispose();
  }
  
  // 根据主题初始化
  chart = echarts.init(chartRef.value, props.theme);
  
  const data = props.chartData[props.chartType];
  
  // 根据主题设置不同配色
  const colors = props.theme === 'dark' 
    ? ['#177ddc', '#49aa19'] 
    : ['#1890ff', '#52c41a'];
    
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['计划数量', '完成数量']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.dates,
      axisLabel: {
        rotate: props.chartType === 'month' ? 0 : 0
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '计划数量',
        type: 'bar',
        data: data.planned,
        barWidth: '40%',
        color: colors[0],
        itemStyle: {
          borderRadius: [4, 4, 0, 0]
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowColor: 'rgba(0,0,0,0.3)'
          }
        },
        animationDelay: function (idx) {
          return idx * 100;
        }
      },
      {
        name: '完成数量',
        type: 'bar',
        data: data.completed,
        barWidth: '40%',
        color: colors[1],
        itemStyle: {
          borderRadius: [4, 4, 0, 0]
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowColor: 'rgba(0,0,0,0.3)'
          }
        },
        animationDelay: function (idx) {
          return idx * 100 + 50;
        }
      }
    ],
    animationEasing: 'elasticOut',
    animationDelayUpdate: function (idx) {
      return idx * 5;
    }
  };
  
  chart.setOption(option);
}

function resizeChart() {
  chart && chart.resize();
}

// 监听图表类型变化
watch(() => props.chartType, () => {
  initChart();
});

// 监听主题变化
watch(() => props.theme, () => {
  initChart();
});

onMounted(() => {
  initChart();
  window.addEventListener('resize', resizeChart);
});

onUnmounted(() => {
  chart && chart.dispose();
  window.removeEventListener('resize', resizeChart);
});
</script>

<style scoped>
.chart {
  width: 100%;
  height: 100%;
}
</style> 